﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Downloader.Domain;
using Downloader.Framework.Queries;

namespace Downloader.Web.Controllers.ViewModels
{
    public class ArticleImgViewModel:IEntityConvert<ArticleContent>
    {
        public ArticleImgViewModel()
        {
            
        }

        public ArticleImgViewModel(ArticleContent article)
        {
            this.Id = article.Id;
            this.Title = article.Title;
            this.ContentText = this.RemoveImg(article.ContentText.Substring(0, 150));
            this.CreateTime = article.CreateTime;
            var imgUrls = this.GetHtmlImageUrlList(article.ContentText);
            if (imgUrls.Length > 0)
            {
                this.ImgUrl = imgUrls[0];
            }
        }
        public int Id { get; set; }
        public string Title { get; set; }
        public string ImgUrl { get; set; }
        public string ContentText { get; set; }
        public DateTime CreateTime { get; set; }

        private string[] GetHtmlImageUrlList(string sHtmlText)
        {
            // 定义正则表达式用来匹配 img 标签
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串
            MatchCollection matches = regImg.Matches(sHtmlText);
            int i = 0;
            string[] sUrlList = new string[matches.Count];

            // 取得匹配项列表
            foreach (Match match in matches)
                sUrlList[i++] = match.Groups["imgUrl"].Value;
            return sUrlList;
        }

        private string RemoveImg(string htmlText)
        {
            string regexstr = @"<img[^>]*>";   
            return  Regex.Replace(htmlText, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        public void From(ArticleContent article)
        {
            this.Id = article.Id;
            this.Title = article.Title;
            this.ContentText = this.RemoveImg(article.ContentText.Substring(0, 150));
            this.CreateTime = article.CreateTime;
            var imgUrls = this.GetHtmlImageUrlList(article.ContentText);
            if (imgUrls.Length > 0)
            {
                this.ImgUrl = imgUrls[0];
            }
        }
    }
}
